import { useForm } from 'react-hook-form';
import { useState, useEffect, useMemo } from 'react';

import * as z from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useService } from '@flowgram.ai/free-layout-editor';
import { Input } from '@douyinfe/semi-ui';

import { McpInfo } from '@/typings/mcp';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
} from '@/components/ui/form';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';

import { Combobox } from '../../ui/combobox';
import { CustomService } from '../../../services/custom-service';

// 定义模型属性的验证 schema
const mcpPropsSchema = z.object({
  name: z.string().min(1, 'MCP服务名称不能为空'),
  type: z.number().int(),
  url: z.string().url(),
  enabled: z.boolean(),
});

type McpProps = z.infer<typeof mcpPropsSchema>;

const mcpTypes = [
  {
    label: 'sse',
    value: 1,
  },
  {
    label: 'std',
    value: 2,
  },
];

export function McpPropsSetting({ mcp, onSaved }: { mcp?: McpInfo; onSaved?: () => void }) {
  const customService = useService(CustomService);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const newMcp = mcp
      ? {
          // 从ChatModelType转换为ModelProps
          name: mcp.Name || '',
          type: mcpTypes.find((mt) => mt.label === mcp.McpType)?.value || 0,
          url: mcp.Url || '',
          enabled: true,
        }
      : {
          // 默认值（包含所有必填字段）
          type: 0,
          name: '',
          url: '',
          enabled: true,
        };
    console.log('mcp', newMcp);
    form.reset(newMcp);
  }, [mcp]);

  // 初始化表单
  const form = useForm<McpProps>({
    resolver: zodResolver(mcpPropsSchema),
    defaultValues: {
      // 默认值（包含所有必填字段）
      type: 0,
      name: '',
      url: '',
      enabled: true,
    },
    mode: 'onSubmit',
    reValidateMode: 'onSubmit',
  });

  // 提交表单
  async function onSubmit(data: McpProps) {
    console.log('submit data', data);
    setLoading(true);
    const m = {
      ID: mcp?.ID || 0,
      Name: form.watch('name'),
      McpType: mcpTypes.find((mt) => mt.value === form.watch('type'))?.label || '',
      Url: form.watch('url'),
    };
    try {
      await customService.saveMcp(m);
      onSaved?.();
    } catch (error) {
      console.error('保存MCP属性失败:', error);
    } finally {
      setLoading(false);
    }
  }

  const typeLabel = useMemo(() => {
    const currentType = form.watch('type');
    return mcpTypes.find((item) => item.value === currentType)?.label || '';
  }, [form.watch('type')]);

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>Mcp属性设置</CardTitle>
        <CardDescription>配置Mcp的详细参数，包括API密钥和生成选项。</CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mcp名称</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入Mcp名称" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mcp类型</FormLabel>
                  <FormControl>
                    <Combobox
                      frameworks={mcpTypes}
                      defaultValue={1}
                      value={field.value}
                      onChange={field.onChange}
                    />
                  </FormControl>
                  <FormDescription>选择Mcp的类型,如sse、std等</FormDescription>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="url"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mcp服务地址</FormLabel>
                  <FormControl>
                    <Input placeholder="http://localhost:11343" {...field} />
                  </FormControl>
                </FormItem>
              )}
            />
          </form>
        </Form>
      </CardContent>
      <CardFooter className="flex justify-end">
        <Button type="submit" disabled={loading} onClick={form.handleSubmit(onSubmit)}>
          {loading ? '保存中...' : '提交'}
        </Button>
      </CardFooter>
    </Card>
  );
}
